/*
 * Copyright (C) 2011-2013 Eric Lasota
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#ifndef __RDX_IO_HPP__
#define __RDX_IO_HPP__

#include "rdx_basictypes.hpp"
#include "rdx_objectmanagement.hpp"

namespace RDX
{
	namespace IO
	{
		struct IFileScanState
		{
			virtual void Close() = 0;
			virtual ObjectManagement::CRef<const Programmability::String> NextFile(OperationContext *ctx, ObjectManagement::IObjectManager *objm) = 0;
		};
		
		struct IFileSystem
		{
			virtual IFileStream *Open(const Char *path, bool write) = 0;
			virtual IFileScanState *ScanDirectory(const Char *directory, const Char *wildcard, const Char *vext) = 0;
		};

		struct IFileStream
		{
			enum SeekType
			{
				SEEK_Start,
				SEEK_Current,
				SEEK_End,
			};

			virtual LargeInt WriteBytes(const void *src, LargeInt numBytes) = 0;
			virtual LargeInt ReadBytes(void *dest, LargeInt numBytes) = 0;
			virtual void Seek(LargeInt offset, SeekType seekType) = 0;
			virtual LargeInt Tell() = 0;
			virtual void Close() = 0;
			virtual bool HasAborted() const = 0;
			virtual void Abort() = 0;

			inline static bool ShouldByteSwap()
			{
				UInt32 RDX_BYTE_ORDER_LITTLE_ENDIAN = 1;
				UInt32 RDX_BYTE_ORDER_BIG_ENDIAN = 0x01000000;

				union
				{
					UInt32 u32;
					UInt8 u8[4];
				} u;
				
				u.u32 = 0;
				u.u8[0] = 1;

				return (u.u32 != RDX_BINARY_STORAGE_ORDER);
			}

			inline LargeInt WriteSwappedBytes(const void *src, LargeInt numBytes)
			{
				UInt8 buffer[16];
				LargeInt bufferOffset = 0;
				LargeInt cumulative = 0;

				const UInt8 *bsrc = reinterpret_cast<const UInt8*>(src) + numBytes;

				for(LargeInt i=0;i<numBytes;i++)
				{
					bsrc--;
					buffer[bufferOffset++] = *bsrc;
					if(bufferOffset == sizeof(buffer))
					{
						cumulative += this->WriteBytes(buffer, sizeof(buffer));
						bufferOffset = 0;
					}
				}
				if(bufferOffset)
					cumulative += this->WriteBytes(buffer, bufferOffset);

				return cumulative;
			}

			inline LargeInt ReadSwappedBytes(void *dest, LargeInt numBytes)
			{
				LargeInt nRead = this->ReadBytes(dest, numBytes);
				if(nRead == numBytes)
				{
					UInt8 *bytes = reinterpret_cast<UInt8*>(dest);
					LargeInt halfPoint = nRead / 2;
					for(LargeInt i=0;i<halfPoint;i++)
					{
						UInt8 temp;
						temp = bytes[i];
						bytes[i] = bytes[nRead-1-i];
						bytes[nRead-1-i] = temp;
					}
				}
				return nRead;
			}

			inline LargeInt ReadSwappableBytes(void *dest, LargeInt numBytes)
			{
				if(ShouldByteSwap())
					return ReadSwappedBytes(dest, numBytes);
				else
					return ReadBytes(dest, numBytes);
			}

			LargeInt WriteSwappableBytes(const void *src, LargeInt numBytes)
			{
				if(ShouldByteSwap())
					return WriteSwappedBytes(src, numBytes);
				else
					return WriteBytes(src, numBytes);
			}

			template<class _Tfrom, class _Tto>
			inline void WriteConverted(_Tfrom val)
			{
				_Tto binVal = static_cast<_Tto>(val);
				if(static_cast<_Tfrom>(binVal) != val)
					this->Abort();
				else
					this->WriteSwappableBytes(&binVal, sizeof(binVal));
			}

			template<class _Tfrom, class _Tto>
			inline bool ReadConverted(_Tto *valOut, bool &overflowed, bool &readFailed)
			{
				_Tfrom fromBin;
				if(this->ReadSwappableBytes(&fromBin, sizeof(_Tfrom)) != sizeof(_Tfrom))
				{
					readFailed = true;
					return false;
				}
				_Tto toVal = static_cast<_Tto>(fromBin);
				if(static_cast<_Tfrom>(toVal) != fromBin)
				{
					overflowed = true;
					return false;
				}
				*valOut = toVal;
				return true;
			}
		};

		struct ITextDeserializer : public IFileStream
		{
			virtual bool CheckToken(const char *str) = 0;
			virtual ObjectManagement::CRef<const Programmability::String> ParseToken(OperationContext *ctx, ObjectManagement::IObjectManager *objm, bool *pIsString, bool shouldReturn = true) = 0;
			virtual void SkipToken(OperationContext *ctx) = 0;
		};
	}
}

#endif
